#!/bin/python
# -*- coding: UTF-8 -*-

import os
import sys
import random
import string
import requests
import getopt
import json

URL = 'http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&pageNo=1&pageSize=100&systemType=PC'
USER_AGENTS = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1','Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0','Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)', ]

vLuckyNumList = []
def main(argv=None):
    if argv == None:
        argv = sys.argv
    nRecentlyCount = 20
    nRedPoolCount = 15
    nBluePoolCount = 10
    nRandomCount = 1
    nStart = 0
    nSkipRedTop = int(nRecentlyCount / 6)
    nSkipBlueTop = int(nRecentlyCount / 6)
    try:
        if not argv is None:
            opts, args = getopt.getopt(argv[1:], "", ["recently=", "redpool=", "bluepool=", "rc=", "start="])
            #print opts 
            for k, v in opts:
                if k == "--recently":
                    nRecentlyCount = int(v)
                elif k == "--redpool":
                    nRedPoolCount = int(v)
                elif k == "--bluepool":
                    nBluePoolCount = int(v)
                elif k == "--rc":
                    nRandomCount = int(v)
                elif k == "--start":
                    nStart = int(v)
                elif k == "--skipr":
                    nSkipRedTop = int(v)
                elif k == "--skipb":
                    nSkipBlueTop = int(v)
            print "nRecentlyCount=%d, nRedPoolCount=%d, nBluePoolCount=%d, nRandomCount=%d, nStart=%d, nSkipRedTop=%d, nSkipBlueTop=%d" % (nRecentlyCount, nRedPoolCount, nBluePoolCount, nRandomCount, nStart, nSkipRedTop, nSkipBlueTop)
    except getopt.GetoptError, err:
        print argv
        return 1

    r = requests.get(url=URL, headers={'User-Agent': random.choice(USER_AGENTS)})  
    vLogList = []
    if r.ok:
        vLogList = r.json()['result']
    else:
        print r
        f = open('ssq.json', 'r')
        vLogList = json.loads(f.read())['result']
        f.close()

    vLogNumsList = []
    for x in vLogList:
        nums = [int(x['blue'])]
        for y in x['red'].split(','):
            nums.append(int(y))
        vLogNumsList.append({'code': int(x['code']), 'nums': nums})

    #选[start, end]中的期数来分析
    start = nStart
    end = start + nRecentlyCount
    for i in range(0, nRandomCount):
        analyseRegion(vLogNumsList[start:end], nRedPoolCount, nBluePoolCount, i, nSkipRedTop, nSkipBlueTop)
    
    vRedLuckyNum2Count = {}
    vBlueLuckyNum2Count = {}
    for x in vLuckyNumList:
        for i in range(len(x)):
            x[i] = x[i][0]
            if i + 1 < len(x):
                vRedLuckyNum2Count[x[i]] = vRedLuckyNum2Count.get(x[i], 0) + 1
            else:
                vBlueLuckyNum2Count[x[i]] = vBlueLuckyNum2Count.get(x[i], 0) + 1
        print x
    vRedLuckyNumberList = vRedLuckyNum2Count.items()
    vRedLuckyNumberList.sort(sortBySecond)
    vRedLuckyNumberList.reverse()
    print vRedLuckyNumberList

    vBlueLuckyNumberList = vBlueLuckyNum2Count.items()
    vBlueLuckyNumberList.sort(sortBySecond)
    vBlueLuckyNumberList.reverse()
    print vBlueLuckyNumberList
    

def sortBySecond(x, y):
    if x[1] > y[1]:
        return 1
    elif x[1] < y[1]:
        return -1

    if x[0] > y[0]:
        return 1
    elif x[0] < y[0]:
        return -1
    return 0

def findRedNumberGapIndex(vSourceList, nFromIndex, nNumber):
    for i in range(nFromIndex, len(vSourceList)):
        if nNumber in vSourceList[i]['nums'][1:]:
            return i - nFromIndex
    return -1

def findBlueNumberGapIndex(vSourceList, nFromIndex, nNumber):
    for i in range(nFromIndex, len(vSourceList)):
        if vSourceList[i]['nums'][0] == nNumber:
            return i - nFromIndex
    return -1

def analyseRegion(vRegionNumsList, nRedPoolCount, nBluePoolCount, nIndex = 0, nSkipRedTop = 0, nSkipBlueTop = 0):
    vRedNumber2CountList = {}
    vBlueNumber2CountList = {}

    vRedNumber2AllGapIndexList = {}
    vBlueNumber2AllGapIndexList = {}
    for index in range(len(vRegionNumsList)):
        for nBlueNumber in range(1, 16 + 1):
            vBlueNumber2AllGapIndexList[nBlueNumber] = vBlueNumber2AllGapIndexList.get(nBlueNumber, []) + [findBlueNumberGapIndex(vRegionNumsList, index, nBlueNumber)]
        for y in range(1, 33 + 1):
            vRedNumber2AllGapIndexList[y] = vRedNumber2AllGapIndexList.get(y, []) + [findRedNumberGapIndex(vRegionNumsList, index, y)]

    vRedGapList = []
    vBlueGapList = []
    index = 0
    for x in vRegionNumsList:
        vRedNumber2GapIndexList = {}
        vBlueNumber2GapIndexList = {}
        nBlueNumber = x['nums'][0]
        vBlueNumber2CountList[nBlueNumber] = vBlueNumber2CountList.get(nBlueNumber, 0) + 1
        vBlueNumber2GapIndexList[nBlueNumber] = findBlueNumberGapIndex(vRegionNumsList, index + 1, nBlueNumber)
        for y in x['nums'][1:]:
            vRedNumber2CountList[y] = vRedNumber2CountList.get(y, 0) + 1
            vRedNumber2GapIndexList[y] = findRedNumberGapIndex(vRegionNumsList, index + 1, y)
        index = index + 1
        if nIndex == 0:
            print vRedNumber2GapIndexList, vBlueNumber2GapIndexList

    vRedNumberList = vRedNumber2CountList.items()
    vRedNumberList.sort(sortBySecond)
    vRedNumberList.reverse()
    vLuckyNumList.append(random.sample(vRedNumberList[nSkipRedTop:nRedPoolCount], 6))

    vBlueNumberList = vBlueNumber2CountList.items()
    vBlueNumberList.sort(sortBySecond)
    vBlueNumberList.reverse()
    vLuckyNumList[len(vLuckyNumList) - 1] = vLuckyNumList[len(vLuckyNumList) - 1] + random.sample(vBlueNumberList[nSkipBlueTop:nBluePoolCount], 1)

    if nIndex == 0:
        for x in vRedNumberList:
            print 'red=>', x, vRedNumber2AllGapIndexList.get(x[0], [])
        for x in vBlueNumberList:
            print 'blue=>', x, vBlueNumber2AllGapIndexList.get(x[0], [])

if __name__ == '__main__':
    sys.exit(main())
